package com.chen.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chen.common.Constant;
import com.chen.dao.pojo.SysUser;
import com.chen.service.LoginService;
import com.chen.service.SysUserService;
import com.chen.util.JWTUtils;
import com.chen.vo.ErrorCode;
import com.chen.vo.Result;
import com.chen.vo.SysUserVo;
import com.chen.vo.param.LoginParam;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author:chenao
 * @DATE:2022/3/10 22:48
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    private static final String slat = "martins";

    @Autowired
    private SysUserService sysUserService;
    /*@Autowired
    private RedisTemplate<String, String> redisTemplate;*/

    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1.检查参数是否合法
         * 2.根据用户名和密码取user表中查询 是否存在
         * 3.如果不存在 登录失败
         * 4.如果存在，使用jwt 生成token 返回给前端
         * 5.token放入redis当中，redis token：user信息 设置过期时间
         * （登录认证的时候 先认证token字符串是否合法，去redis认证是否存在）
         */
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //加密盐
        password = DigestUtils.md5Hex(password + slat);
        SysUser sysUser = sysUserService.findUser(username, password);
        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        if (sysUser.getStatus()==0){
            return Result.fail(ErrorCode.USER_BAN.getCode(), ErrorCode.USER_BAN.getMsg());
        }
        //如果用户认证通过，根据用户ID生成唯一token，并放入redis中保存一天
        String token = JWTUtils.createToken(sysUser);
        //将token放入redis中，string类型且设置过期时间
        //redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(sysUser,sysUserVo);
        sysUserVo.setRole(Constant.getname(sysUser.getRole()));
        sysUserVo.setToken(token);
        return Result.success(sysUserVo);
    }

    @Override
    public SysUser checkToken(String token) {
        Map<String, Object> map = JWTUtils.checkToken(token);
        //如果token无效或过期会返回null
        if(map==null){
            log.info("token无效或过期");
            return null;
        }
        String role = (String) map.get("role");
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        SysUser sysUser = new SysUser();
        sysUser.setRole(role);
        sysUser.setUsername(username);
        sysUser.setPassword(password);
        return sysUser;
    }

    @Override
    public Result logout(String token) {
        return null;
    }

    @Override
    public Result register(LoginParam loginParam) {
        return null;
    }
}
